import { Context, Next } from 'koa';
import logger from '@/utils/logger';
import { AppContext } from '@/types';

/**
 * 请求日志中间件
 */
export default async function requestLogger(ctx: Context, next: Next) {
  const appCtx = ctx as AppContext;
  const start = Date.now();

  // 记录请求开始
  logger.info(`--> ${ctx.method} ${ctx.url}`, {
    ip: ctx.ip,
    userAgent: ctx.get('user-agent'),
    tenant: appCtx.state.tenant?.subdomain,
    user: appCtx.state.user?.email,
  });

  try {
    await next();

    // 记录请求结束
    const ms = Date.now() - start;
    logger.info(`<-- ${ctx.method} ${ctx.url} ${ctx.status} ${ms}ms`, {
      status: ctx.status,
      responseTime: ms,
    });
  } catch (error) {
    // 记录错误
    const ms = Date.now() - start;
    logger.error(`<-- ${ctx.method} ${ctx.url} ERROR ${ms}ms`, {
      error: error instanceof Error ? error.message : String(error),
      responseTime: ms,
    });
    throw error;
  }
}


